package util;

import bean.NodeVo;

import java.util.List;
import java.util.stream.Collectors;

public class NodeUtil {

    /**
     * list转tree
     *
     * @date 2022/3/17
     */
    public static List<? extends NodeVo> listWithTree(List<? extends NodeVo> nodeList) {
        // 先找到一级父类，再通过级联去查询子类菜单
        List<NodeVo> topLevel = nodeList.stream().filter(node ->
                node.getPid() == 0     //查询父类
        ).map((node) -> {
            node.setChildren(getChildren(node, nodeList)); //查询子类菜单
            return node;
        }).sorted((node1, node2) -> {
            // 排序
            return (node1.getSort() == null ? 0 : node1.getSort()) - (node2.getSort() == null ? 0 : node2.getSort());
        }).collect(Collectors.toList());
        return topLevel;
    }

    /**
     * 递归查找所有菜单的子类菜单
     *
     * @date 2022/3/17
     */
    private static List<NodeVo> getChildren(NodeVo root, List<? extends NodeVo> all) {
        List<NodeVo> children = all.stream().filter(node -> {
            return node.getPid() == root.getId();
        }).map(node -> {
            // 1、递归找到子菜单
            node.setChildren(getChildren(node, all));
            return node;
        }).sorted((menu1, menu2) -> {
            // 2、菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }
}
